
import json
from django.shortcuts import render
from django.views.generic.base import View
from django.http import HttpResponse
from django.conf import settings
from django.db.models import Q
from django.core.exceptions import ObjectDoesNotExist

from criterion.forms import ReviewReferenceUpdateForm
from utils.mixin_utils import LoginRequiredMixin
from rbac.models import Menu
from django.core.serializers.json import DjangoJSONEncoder

from .models import ReviewClause, ReviewKey, ReviewReference,Criteria
from django.shortcuts import get_object_or_404

# from .models import SystemSetup
# from .forms import SystemSetupForm
# Create your views here.

def test(request):
    # clause_list=ReviewClause.objects.all().order_by('id')
    # for clause in clause_list:
    #     clause.pk = None
    #     clause.criteria_id=2
    #     if clause.level != "1":
    #         clause.parent_id=clause.parent_id+1068
    #     print(clause)
    #     clause.save()
    # key_list=ReviewKey.objects.all().order_by('id')
    # for key in key_list:
    #     key.pk = None
    #     key.clause_id=key.clause_id+1068
    #     print(key)
    #     key.save()
    return HttpResponse("good2")


class CriteriaView(LoginRequiredMixin, View):
    """
    标准查询入口
    """
    def get(self, request, criteria_id=3,clause_id=2):
        # ret = Menu.getMenuByRequestUrl(url=request.path_info)
        # ret.update(SystemSetup.getSystemSetupLastData())
        if criteria_id==1 and clause_id==2:
            clause_id = 2
        if criteria_id==2 and clause_id==2:
            clause_id = 1070
        if criteria_id==3 and clause_id==2:
            clause_id = 4146
        criteria=Criteria.objects.get(pk=criteria_id)
        if  ReviewClause.objects.filter(criteria=criteria).filter(level="1").filter(id=clause_id).exists():
            clause_id=ReviewClause.objects.filter(criteria=criteria).filter(parent=clause_id).first().id

        clause_now=ReviewClause.objects.filter(criteria=criteria).get(id=clause_id)
        ###############一级菜单的渲染###################################
        level1_all = ReviewClause.objects.filter(criteria=criteria).filter(level="1").order_by("sort")
        clause_parent=clause_now.parent
        ###############二级级菜单的渲染###################################
        level2_all=ReviewClause.objects.filter(level="2").filter(criteria=criteria).filter(parent=clause_parent).order_by("sort")
        ###############三级目录的渲染###################################
        level3_all = ReviewClause.objects.filter(level="3").filter(criteria=criteria).filter(parent=clause_now).order_by("sort")

        is_superuser=False
        if self.request.user.is_superuser:
            is_superuser = True

        return render(request, 'criterion/criteria.html',locals())
        # return render(request, 'criterion/criterion_view.html',locals())

class CriterionEditView(LoginRequiredMixin, View):
    """
    标准模块入口
    """
    def get(self, request):
        # l1_now=request.get["l1"]
        # l2_now=request.get["l2"]

        l1 = ReviewClause.objects.filter(level="1")
        l2 = ReviewClause.objects.filter(level="2").first()
        print(request)

        mList = ReviewClause.objects.all()

        _data = [
            {
                'id': x.id,
                'name': x.name+x.desc,
                'pId': x.parent.id if x.parent else 0,
                'open': 0
            } for x in mList
        ]

        return render(request, 'criterion/criterion_edit.html',{"l1":l1,"data":_data})

class JsonLevel6ClauseListView(LoginRequiredMixin, View):
    """
    返回所有叶子条款Json数据
    """

    def get(self, request):
        fields = ['id', 'name', 'desc']
        filters = dict()
        if 'select' in request.GET and request.GET.get('select'):
            filters['is_active'] = request.GET.get('select')
        ret = dict(data=list(ReviewClause.objects.filter(level="6").filter(**filters).values(*fields).order_by("id")))
        return HttpResponse(json.dumps(ret, cls=DjangoJSONEncoder), content_type='application/json')


class RefContentView(LoginRequiredMixin, View):
    """
    获取参考资料
    """
    def get(self, request, num):
        ref = ReviewReference.objects.get(id=num)
        ret=""
        if ref:
            ret=ref.desc
        return HttpResponse(ref.desc)
class ReviewReferenceDetailView(LoginRequiredMixin, View):
    """
    条款参考文件：查看、修改、新建数据
    """

    def get(self, request):
        try:
            ret = dict()
            if 'clause_id' in request.GET and request.GET['clause_id'] and 'ref_type' in request.GET and request.GET['ref_type']:
                # ref = get_object_or_404(ReviewReference, pk=request.GET.get('clause_id'))
                clause=ReviewClause.objects.get(pk=request.GET['clause_id'])
                clause_id=request.GET['clause_id']
                ref_type=request.GET['ref_type']
                obj, created = ReviewReference.objects.get_or_create(
                    clause=clause,
                    type=ref_type,
                )
                id=obj.id
                ref_type=obj.get_type_display()

                form = ReviewReferenceUpdateForm(instance=obj)

                return render(request, 'criterion/criterion_reference.html', {"form": form,"clause":clause,"ref_type":ref_type,"id":id})
        except Exception as e:
            return HttpResponse(e)
            # return HttpResponse("没有这个条款")

    def post(self, request):
        res = dict(result=False)
        # if request.method == 'POST':
        #     # 接受request.POST参数构造form类的实例
        #     form = ReviewReferenceUpdateForm(request.POST)
        #     print(form)
            # 验证数据是否合法
            # if form.is_valid():
            #     # 处理form.cleaned_data中的数据
            #     form.save()
            #     res['result'] = True
                # 重定向到一个新的URL
                # return HttpResponse(json.dumps(res), content_type='application/json')
        if 'id' in request.POST and request.POST['id']:
            obj = get_object_or_404(ReviewReference, pk=request.POST['id'])
            # clause = obj.clause
            # print("clause",clause)
        # else:
        #     obj = ReviewReference()
        # form = ReviewReferenceUpdateForm(request.POST, instance=obj)
        # if form.is_valid():
        #     form.save()
            obj.desc=request.POST['desc']
            obj.save()
            res['result'] = True
        return HttpResponse(json.dumps(res), content_type='application/json')
